package com.tm.mygsyplayer;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder;
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack;
import com.shuyu.gsyvideoplayer.utils.CommonUtil;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.tm.mygsyplayer.utils.ScrollCalculatorHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RecyclerAutoPlayActivity extends AppCompatActivity {

    RecyclerView mRecyclerView;

    private LinearLayoutManager mLayoutManager;
    private List<String> urlList = new ArrayList<>();

    boolean mFull = false;
    ScrollCalculatorHelper scrollCalculatorHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recycler_auto_play);

        mRecyclerView = findViewById(R.id.video_recyclerView);

        makeDatas();

        //限定范围为屏幕一半的上下偏移180
        int playTop = CommonUtil.getScreenHeight(this) / 2 - CommonUtil.dip2px(this, 180);
        int playBottom = CommonUtil.getScreenHeight(this) / 2 + CommonUtil.dip2px(this, 180);

        //自定播放帮助类
        scrollCalculatorHelper = new ScrollCalculatorHelper(R.id.video_item_player, playTop, playBottom);

        RecyclerNormalAdapter adapter = new RecyclerNormalAdapter(this, urlList);
        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            int firstVisibleItem, lastVisibleItem;

            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                scrollCalculatorHelper.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition();
                lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();

                //这是滑动自动播放的代码
                if (!mFull) {
                    scrollCalculatorHelper.onScroll(recyclerView, firstVisibleItem, lastVisibleItem, lastVisibleItem - firstVisibleItem);
                }
            }
        });
    }

    private void makeDatas() {
        urlList.add("http://chuangfen.oss-cn-hangzhou.aliyuncs.com/public/attachment/201805/100651/201805181532123423.mp4");

        urlList.add("http://gslb.miaopai.com/stream/Kkfwus-oq0FvDYFSM2ZdUA7fpvF~Eb7AOgaggw__.mp4?vend=miaopai&ssig=985a58a4a43d9dcb51e498d922f0cb60&time_stamp=1568709306250&mpflag=32&unique_id=1568705667098034");
        urlList.add("http://1255550251.vod2.myqcloud.com/103cb269vodtranscq1255550251/f70671555285890785770127834/v.f30.mp4");
        urlList.add("http://1255550251.vod2.myqcloud.com/103cb269vodtranscq1255550251/62003ff05285890784523774331/v.f40.mp4");
        urlList.add("http://1255550251.vod2.myqcloud.com/103cb269vodtranscq1255550251/10aedb4b5285890793337300725/v.f30.mp4");
        urlList.add("http://1255550251.vod2.myqcloud.com/3952c4c1vodcq1255550251/0bf19dd35285890790259710935/qm6enMGetG0A.mp4");
    }

    class RecyclerNormalAdapter extends RecyclerView.Adapter<RecyclerNormalAdapter.NormalViewHolder> {

        private static final String TAG = "RecyclerNormalAdapter";
        private List<String> datas;
        private Context mContext;

        public RecyclerNormalAdapter(Context context, List<String> urls) {
            this.mContext = context;
            this.datas = urls;
        }

        public void setDatas(List<String> datas) {
            this.datas = datas;
            notifyDataSetChanged();
        }

        @NonNull
        @Override
        public NormalViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new NormalViewHolder(LayoutInflater.from(mContext).inflate(R.layout.rv_item_player, parent, false));
        }

        @Override
        public void onBindViewHolder(@NonNull NormalViewHolder holder, int position) {
            String url = datas.get(position);
            String title = "测试视频";
            //增加封面
            holder.imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            holder.imageView.setImageResource(R.mipmap.ic_video_cover);

            if (holder.imageView.getParent() != null) {
                ViewGroup viewGroup = (ViewGroup) holder.imageView.getParent();
                viewGroup.removeView(holder.imageView);
            }


            Map<String, String> header = new HashMap<>();
            header.put("ee", "33");
            //防止错位，离开释放
            //gsyVideoPlayer.initUIState();
            holder.gsyVideoOptionBuilder
                    .setIsTouchWiget(false)
                    .setThumbImageView(holder.imageView)
                    .setUrl(url)
                    .setVideoTitle(title)
                    .setCacheWithPlay(false)
                    .setRotateViewAuto(true)
                    .setLockLand(true)
                    .setPlayTag(TAG)
                    .setMapHeadData(header)
                    .setShowFullAnimation(true)
                    .setNeedLockFull(true)
                    .setPlayPosition(position)
                    .setVideoAllCallBack(new GSYSampleCallBack() {
                        @Override
                        public void onPrepared(String url, Object... objects) {
                            super.onPrepared(url, objects);
//                            if (!holder.gsyVideoPlayer.isIfCurrentIsFullscreen()) {
//                                //静音
//                                GSYVideoManager.instance().setNeedMute(true);
//                            }

                        }

                        @Override
                        public void onQuitFullscreen(String url, Object... objects) {
                            super.onQuitFullscreen(url, objects);
                            //全屏不静音
                            GSYVideoManager.instance().setNeedMute(true);
                        }

                        @Override
                        public void onEnterFullscreen(String url, Object... objects) {
                            super.onEnterFullscreen(url, objects);
                            GSYVideoManager.instance().setNeedMute(false);
                            holder.gsyVideoPlayer.getCurrentPlayer().getTitleTextView().setText((String) objects[0]);
                        }

                        @Override
                        public void onClickBlank(String url, Object... objects) {
                            super.onClickBlank(url, objects);
                        }
                    }).build(holder.gsyVideoPlayer);

            //增加title
            holder.gsyVideoPlayer.getTitleTextView().setVisibility(View.GONE);

            //设置返回键
            holder.gsyVideoPlayer.getBackButton().setVisibility(View.GONE);

            //设置全屏按键功能
            holder.gsyVideoPlayer.getFullscreenButton().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    resolveFullBtn(holder.gsyVideoPlayer);
                }
            });
        }

        /**
         * 全屏幕按键处理
         */
        private void resolveFullBtn(final StandardGSYVideoPlayer standardGSYVideoPlayer) {
            standardGSYVideoPlayer.startWindowFullscreen(mContext, true, true);
        }

        @Override
        public int getItemCount() {
            return datas.size();
        }

        class NormalViewHolder extends RecyclerView.ViewHolder {

            StandardGSYVideoPlayer gsyVideoPlayer;

            ImageView imageView;
            GSYVideoOptionBuilder gsyVideoOptionBuilder;

            public NormalViewHolder(@NonNull View itemView) {
                super(itemView);
                gsyVideoPlayer = itemView.findViewById(R.id.video_item_player);
                imageView = new ImageView(mContext);
                gsyVideoOptionBuilder = new GSYVideoOptionBuilder();
            }
        }

    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        //如果旋转了就全屏
        if (newConfig.orientation != ActivityInfo.SCREEN_ORIENTATION_USER) {
            mFull = false;
        } else {
            mFull = true;
        }

    }

    @Override
    public void onBackPressed() {
        if (GSYVideoManager.backFromWindowFull(this)) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        GSYVideoManager.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        GSYVideoManager.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        GSYVideoManager.releaseAllVideos();
    }

}
